/*
 * Copyright (c) 2017,安徽皖通科技股份有限公司 All rights reserved.
 */

package com.wttech.dzzf.process.service.fill;

import com.wtkj.vo.dzzf.base.kfwd.CardInfo;
import com.wttech.dzzf.process.dao.FillMissingDataDao;
import com.wttech.dzzf.process.dao.TransferUserInfoDao;
import com.wttech.dzzf.process.service.base.BaseInfoService;
import com.wttech.dzzf.process.util.BusinessUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;

import static com.wttech.dzzf.process.constant.UserConstants.DEFAULT_PROCESS_NUM;

/**
 * 填充卡片信息
 *
 * @author MaShibo
 * @date 2017/12/11.
 */
@Service
public class FillCardInfosService {

	private static final Logger LOGGER = LoggerFactory.getLogger(FillCardInfosService.class);

	@Resource
	private FillMissingDataDao fillMissingDataDao;

	@Resource
	private TransferUserInfoDao transferUserInfoDao;

	@Resource
	private BaseInfoService baseInfoService;

	@Resource
	private ThreadPoolTaskExecutor executor;

	void fill() {
		while (true) {
			List<CardInfo> cardInfos = fillMissingDataDao.queryMissingInfoCards(DEFAULT_PROCESS_NUM);
			if (CollectionUtils.isEmpty(cardInfos)) {
				LOGGER.info("卡片相关信息填充完毕");
				return;
			}
			List<Future<Void>> futures = new ArrayList<>(cardInfos.size());
			LOGGER.info("开始填充卡片信息");
			cardInfos.forEach(cardInfo -> futures.add(executor.submit(() -> {
				fillCardInfo(cardInfo);
				return null;
			})));
			baseInfoService.getFutureResult(futures);
		}
	}

	void fillCardInfo(CardInfo cardInfo) {
		try {
			String topClass = cardInfo.getTopClass();
			Integer ecardType = cardInfo.getECardType();
			String cardType = BusinessUtils.determineCardType(topClass, ecardType).toString();

			CardInfo update = new CardInfo();
			Integer bindAccountType = Integer.valueOf(cardType.substring(1, 2));
			Integer bindCardType = Integer.valueOf(cardType.substring(2, 3));
			Integer cardBrand = BusinessUtils.determineCardBrand(cardInfo.getCardNetID() + cardInfo.getECardNo(), ecardType, topClass);

			update.setCardInfoId(cardInfo.getCardInfoId());
			update.setBindAccountType(bindAccountType);
			update.setBindCardType(bindCardType);
			update.setCardBrand(cardBrand);
			transferUserInfoDao.updateDzzfObject(update);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}
}
